package array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * leet-code(15) 三数和
 *
 * @author Ringo
 * @date 2021/8/17 21:58
 */
public class ThreeSum {

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        System.out.println(threeSum(nums));
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        // 三数和
        if (nums == null || nums.length < 3) return new ArrayList<>();
        Arrays.sort(nums);
        if (nums[0] > 0) return new ArrayList<>();
        int n = nums.length;
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < n - 2; ++i) {
            // 去重
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int target = -nums[i];
            int lo = i + 1, hi = n - 1;
            while (lo < hi) {
                if (nums[lo] + nums[hi] == target) {
                    ans.add(Arrays.asList(nums[i], nums[lo], nums[hi]));
                    ++lo;
                    --hi;
                    // 去重
                    while (lo < hi && nums[lo] == nums[lo - 1]) ++lo;
                    while (lo < hi && nums[hi] == nums[hi + 1]) --hi;
                } else if (nums[lo] + nums[hi] < target) {
                    ++lo;
                } else {
                    --hi;
                }
            }
        }
        return ans;
    }
}
